﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMS.Base;
using DMS.BaseClass;
using DMS.Business.Modules.Organization;
using DMS.Business.Utility;
using System.Data.Common;
using System.Web.UI.HtmlControls;

namespace DMS.Web.Common.Controls
{
    public partial class DetpartmentListCtrl : ListControlBase
    {
        #region 成员属性
        /// <summary>
        /// 上级部门ID
        /// </summary>
        public string ParentDeptID
        {
            get
            {
                return this.hidPDeptID.Value;
            }
            set
            {
                this.hidPDeptID.Value = value;
            }
        }
        public string ParentDpetIDPath
        {
            get
            {
                return this.hidPDeptIDPath.Value;
            }
            set
            {
                this.hidPDeptIDPath.Value = value;
            }
        }
        /// <summary>
        /// 启用搜索
        /// </summary>
        public bool EnableSearch
        {
            get
            {
                return this.dvSearch.Visible;
            }
            set
            {
                this.dvSearch.Visible = value;
            }
        }
        /// <summary>
        /// 页大小限制
        /// </summary>
        public int PageLimte
        {
            get
            {
                return this.pager.PageSize;
            }
            set
            {
                this.pager.PageSize = value;
            }
        }
        private string _OnClientSelectBtnClick = string.Empty;
        public string OnClientSelectBtnClick
        {
            get
            {
                return this._OnClientSelectBtnClick;
            }
            set
            {
                this._OnClientSelectBtnClick = value;
            }
        }
        protected override List<Control> ControlSet
        {
            get
            {
                List<Control> ctrls = new List<Control>();
                ctrls.Add(this.imgSelectDept);

                return ctrls;
            }
        }
        protected override List<string> ControlSetInGrid
        {
            get
            {
                List<string> ctrlIds = new List<string>();

                return ctrlIds;
            }
        }
        protected override Dictionary<int, string> ColumnStateSettings
        {
            get
            {
                Dictionary<int, string> settings = new Dictionary<int, string>();
                foreach (ListItem item in this.lbGridColState.Items)
                {
                    try
                    {
                        int key = Convert.ToInt32(item.Text);
                        string value = item.Value;
                        settings.Add(key, value);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.LogException(ex);
                    }
                }

                return settings;
            }
        }
        protected override WebControl MainListControl
        {
            get
            {
                return this.dgDeptList;
            }
        }
        #endregion

        #region 界面事件
        /// <summary>
        /// 控件加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.GetParams();

            if (!IsPostBack)
            {
                if(String.IsNullOrEmpty(hidPDeptID.Value)){
                    Department defaultParent = UserHelper.GetDepartmentByName("广州移动本部");
                    hidPDeptID.Value = defaultParent.ID.ToString();
                }
                
                this.InitDataList();
            }
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void dgDeptList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
            {
                return;
            }

            Department dept = e.Item.DataItem as Department;
            if (dept == null)
            {
                return;
            }

            HtmlAnchor lkSelectBtn = e.Item.FindControl("lkSelectBtn") as HtmlAnchor;
            if (lkSelectBtn != null && !string.IsNullOrEmpty(this._OnClientSelectBtnClick))
            {
                string script = this._OnClientSelectBtnClick;
                if (this._OnClientSelectBtnClick.Contains("%ActorType%"))
                {
                    script = script.Replace("%ActorType%", dept.ActorType.ToString());
                }
                if (this._OnClientSelectBtnClick.Contains("%ID%"))
                {
                    script = script.Replace("%ID%", dept.ID.ToString());
                }
                if (this._OnClientSelectBtnClick.Contains("%Name%"))
                {
                    script = script.Replace("%Name%", dept.Name);
                }
                if (this._OnClientSelectBtnClick.Contains("%DeptFullName%"))
                {
                    script = script.Replace("%DeptFullName%", dept.FullName);
                }
                lkSelectBtn.Attributes["onclick"] = string.Format("javascript:{0};", script);
            }
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void pager_PageChanged(object sender, EventArgs e)
        {
            this.InitDataList();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.pager.GoToPage(1);
            this.InitDataList();
        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 获取参数
        /// </summary>
        private void GetParams()
        {
            // 部门ID
            Department dept = null;
            if (!IsPostBack && !string.IsNullOrEmpty(Request["DeptID"]))
            {
                try
                {
                    dept = UserHelper.GetDepartmentByID(Request["DeptID"].ToString());
                }
                catch (Exception ex)
                {
                    string code = LogHelper.LogException(ex);
                    string msg = string.Format("没法正常读取参数，请与管理员联系。\\r\\n错误码：", code);
                    ClientHelper.Instance.Alert(msg);
                }

                if (dept != null)
                {
                    this.hidPDeptID.Value = dept.ID.ToString();
                    this.hidPDeptIDPath.Value = dept.IDPath;
                    this.txtPDeptName.Text = dept.Name;
                }
                else
                {
                    List<Department> rootDepts = UserHelper.GetRootDepartments();
                    if (rootDepts.Count > 0)
                    {
                        Department rootDept = rootDepts[0];
                        this.hidPDeptID.Value = rootDept.ID.ToString();
                        this.hidPDeptIDPath.Value = rootDept.IDPath;
                        this.txtPDeptName.Text = rootDept.Name;
                    }
                }
            }

        }
        /// <summary>
        /// 初始化列表
        /// </summary>
        public void InitDataList()
        {
            int total = 0;
            string condition = string.Empty;
            List<DbParameter> parameters = new List<DbParameter>();

            Department pDept = null;
            string pDeptID = "";
            if (!string.IsNullOrEmpty(this.hidPDeptID.Value))
            {
                pDeptID = this.hidPDeptID.Value;
                pDept = UserHelper.GetDepartmentByID(pDeptID);
            }
            if (pDept == null)
            {
                List<Department> depts = UserHelper.GetRootDepartments();
                if (depts.Count > 0)
                {
                    pDept = depts[0];
                }
            }
            if (pDept != null)
            {
                this.txtPDeptName.Text = pDept.Name;

                if (this.cbDisplaySub.Checked)
                {
                    condition += " AND [DeptIDPath] Like @DeptIDPath + '>%'";
                    DbParameter paramer = DBHelper.CreateParamer();
                    paramer.ParameterName = "DeptIDPath";
                    paramer.Value = pDept.IDPath.ToString().ToUpper();

                    parameters.Add(paramer);
                }
                else
                {
                    condition += " AND [P_DeptID] = @P_DeptID";
                    DbParameter paramer = DBHelper.CreateParamer();
                    paramer.ParameterName = "P_DeptID";
                    paramer.Value = pDept.ID.ToString();

                    parameters.Add(paramer);
                }
            }
            if (!string.IsNullOrEmpty(this.txtDeptName.Text))
            {
                condition += " AND [DeptName] LIKE '%'+@DeptName+'%'";
                DbParameter paramer = DBHelper.CreateParamer();
                paramer.ParameterName = "DeptName";
                paramer.Value = this.txtDeptName.Text;

                parameters.Add(paramer);
            }

            List<Department> deptsToBind = UserHelper.GetDepartments(pager.PageSize, pager.CurrentPageIndex, out total, condition, parameters);
            this.dgDeptList.DataSource = deptsToBind;
            this.dgDeptList.DataBind();

            this.pager.RecordCount = total;


            // 处理空数据
            if (total == 0)
            {
                this.dgDeptList.Visible = false;
                this.pager.Visible = false;
                this.dvEmpty.Visible = true;
            }
            else
            {
                this.dgDeptList.Visible = true;
                this.pager.Visible = true;
                this.dvEmpty.Visible = false;
            }
        }
        #endregion
    }
}